package com.trevor.action;

import java.io.FileInputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.trevor.services.InformService;

public class DownloadAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
//		response.reset();
		InformService is=new InformService();
		String dataid=request.getParameter("dataid");
		String add=is.getDownAdress(dataid);
		String name=is.getDownName(dataid);
		//String realpath=request.getServletContext().getRealPath(add+"\\"+name);
		String realpath=this.getServlet().getServletContext().getRealPath(add);
		System.out.println(realpath);
		 response.addHeader("Content-Disposition","attachment;filename=" + name);
//		OutputStream os=response.getOutputStream();
		 OutputStream os=null;
		 FileInputStream fi=null;
		 try{
			 os=response.getOutputStream();
			 fi=new FileInputStream(realpath);
			 
			 byte[] b=new byte[1024];
			 int i=0;
			 while((i=fi.read(b))>0){
				 os.write(b, 0, i);
			 }
			 os.flush();
		 }catch(Exception e){
			 e.printStackTrace();
		 }finally{
			 if(fi!=null){
				 fi.close();
			 }
			 if(os!=null){
				 os.close();
			 }
		 }
		return null;
	}

}
